<?php
class Admincp_NewsController extends Main_Controller_Action
{
    private $_arrParam;
    private $_model;
    private $_locale;

    public function init()
    {
        $this->loadTemplates('admin');
        $this->view->headTitle('Quản lý dịch vụ');
        $this->_arrParam = $this->_request->getParams();
        $this->_model = new Admincp_Model_News();
        $this->_locale = 'vi';
    }

    public function preDispatch()
    {
        $auth = Zend_Auth::getInstance();
        if(!$auth->hasIdentity()) {
            if($this->_request->getActionName() != 'login')
                $this->_redirect('admincp/index/login');
        }
    }

    public function indexAction()
    {
        if($_POST['add']) {
            $this->_redirect('admincp/news/create');
        }
        if($_POST['delete']) {
            $listId = $this->_arrParam['check'];
            $this->_model->deleteMultiNews($listId);
            $this->_redirect($_SERVER['HTTP_REFERER']);
        }

        $adapter = new Zend_Paginator_Adapter_DbSelect($this->_model->listNews($this->_locale));
        $paginator = new Zend_Paginator($adapter);
        $paginator->setItemCountPerPage(40);
        $paginator->setPageRange(5);
        $currentPage = $this->_request->getParam('page', 1);
        $paginator->setCurrentPageNumber($currentPage);
        $this->view->data = $paginator;
        $this->view->total = $paginator->getTotalItemCount();
    }

    public function createAction()
    {
        $language = new Admincp_Model_Language();
        $category = new Admincp_Model_Category();
        $this->view->language = $language->listLanguageFull();
        $this->view->category = $category->listCategorySelectbox();

        if($this->_request->isPost()) {
            $title['vi'] = trim(strip_tags($this->_arrParam['title-vi']));
            $title['zh'] = trim(strip_tags($this->_arrParam['title-zh']));
            $title['en'] = trim(strip_tags($this->_arrParam['title-en']));
            $title['trv'] = trim(strip_tags($this->_arrParam['title-trv']));
            $description['vi'] = trim(stripslashes($this->_arrParam['description-vi']));
            $description['zh'] = trim(stripslashes($this->_arrParam['description-zh']));
            $description['en'] = trim(stripslashes($this->_arrParam['description-en']));
            $description['trv'] = trim(stripslashes($this->_arrParam['description-trv']));
            $category_id = (int) $this->_arrParam['category_id'];
            $upload         = new Zend_File_Transfer_Adapter_Http();
            $info           = $upload->getFileInfo();
            $image          = $upload->getFileName('image', false);

            // Resize Image
            $resize = new Zend_Filter_ImageSize();
            preg_match('#\.([^\.]+)$#', $image, $matches);
            $fileExtension  = $matches[1];
            $fileName = 'pic_' . time() . mt_rand(5, 99999999);
            $newFileName1 = $fileName . '.' . $fileExtension;

            $options = array('target' => BASE_PATH . '/public/files/news/' . $newFileName1,'overwrite'=>true);
            $upload->addFilter('Rename',$options,'image');
            $upload->receive('image');
            $output = $resize->setHeight(400)
                ->setWidth(500)
                ->setThumnailDirectory(BASE_PATH . '/public/files/news/')
                ->filter(BASE_PATH . '/public/files/news/' . $newFileName1);
            header('Content-Type: image/jpeg');
            $fh = fopen($output, 'r');
            fpassthru($fh);
            fclose($fh);
            $newFileName = $fileName . '-500x400.' . strtolower($fileExtension);
            unlink(PUBLIC_PATH . '/files/news/' . $newFileName1);

            // Insert to database
            $strFlex = new Zendvn_Filter_RemoveCircumflex();
            $common = new Admincp_Model_Common();
            $data_news = array(
                'image' => $newFileName,
                'category_id' => $category_id,
                'create_date' => date('Y-m-d H:i:s'),
                'status' => 2,
            );
            $news_id = $this->_model->addNews($data_news);
            foreach($title as $key=>$value) {
                foreach($this->view->language as $lang) {
                    if($key == $lang['locale']) {
                        $data = array(
                            'news_id' => $news_id,
                            'language_id' => $lang['id'],
                            'title' => $value,
                            'short_description' => $common->cut_string(strip_tags($description[$key]), 300, 1),
                            'description' => $description[$key],
                            'title_plaintext' => $strFlex->filter(strtolower($value)),
                        );
                        $this->_model->addNewsLanguage($data);
                        break;
                    }
                }
            }
            $this->_redirect('admincp/news');
        }
    }

    public function editAction()
    {
        $id = (int) $this->_arrParam['id'];
        $language = new Admincp_Model_Language();
        $category = new Admincp_Model_Category();
        $this->view->data = $this->_model->getNewsLanguageById($id);
        $this->view->news = $this->_model->getNewsById($id);
        $this->view->language = $language->listLanguageFull();
        $this->view->category = $category->listCategorySelectbox();

        if($this->_request->isPost()) {
            $title['vi'] = trim(strip_tags($this->_arrParam['title-vi']));
            $title['zh'] = trim(strip_tags($this->_arrParam['title-zh']));
            $title['en'] = trim(strip_tags($this->_arrParam['title-en']));
            $title['trv'] = trim(strip_tags($this->_arrParam['title-trv']));
            $description['vi'] = trim(stripslashes($this->_arrParam['description-vi']));
            $description['zh'] = trim(stripslashes($this->_arrParam['description-zh']));
            $description['en'] = trim(stripslashes($this->_arrParam['description-en']));
            $description['trv'] = trim(stripslashes($this->_arrParam['description-trv']));
            $category_id = (int) $this->_arrParam['category_id'];
            $upload         = new Zend_File_Transfer_Adapter_Http();
            $info           = $upload->getFileInfo();
            $image          = $upload->getFileName('image', false);

            if(!empty($image)) {
                // Resize Image
                $resize = new Zend_Filter_ImageSize();
                preg_match('#\.([^\.]+)$#', $image, $matches);
                $fileExtension  = $matches[1];
                $fileName = 'pic_' . time() . mt_rand(5, 99999999);
                $newFileName1 = $fileName . '.' . $fileExtension;

                $options = array('target' => BASE_PATH . '/public/files/news/' . $newFileName1,'overwrite'=>true);
                $upload->addFilter('Rename',$options,'image');
                $upload->receive('image');
                $output = $resize->setHeight(400)
                    ->setWidth(500)
                    ->setThumnailDirectory(BASE_PATH . '/public/files/news/')
                    ->filter(BASE_PATH . '/public/files/news/' . $newFileName1);
                header('Content-Type: image/jpeg');
                $fh = fopen($output, 'r');
                fpassthru($fh);
                fclose($fh);
                $newFileName = $fileName . '-500x400.' . strtolower($fileExtension);
                unlink(PUBLIC_PATH . '/files/news/' . $newFileName1);
                unlink(PUBLIC_PATH . '/files/news/' . $this->view->news['image']);
            }

            // Insert to database
            $strFlex = new Zendvn_Filter_RemoveCircumflex();
            $common = new Admincp_Model_Common();
            $data_news = array(
                'category_id' => $category_id,
            );
            if(!empty($image)) {
                $data_news['image'] = $newFileName;
            }
            $this->_model->updateNews($data_news, $id);
            foreach($title as $key=>$value) {
                foreach($this->view->language as $lang) {
                    if($key == $lang['locale']) {
                        $data = array(
                            'language_id' => $lang['id'],
                            'title' => $value,
                            'short_description' => $common->cut_string(strip_tags($description[$key]), 300, 1),
                            'description' => $description[$key],
                            'title_plaintext' => $strFlex->filter(strtolower($value)),
                        );
                        $this->_model->updateNewsLanguage($data, $id);
                        break;
                    }
                }
            }
            $this->_redirect('admincp/news');
        }
    }

    public function deleteAction()
    {
        $id = (int) $this->_arrParam['id'];
        $this->_model->deleteNews($id);
        $this->_redirect($_SERVER['HTTP_REFERER']);
    }

    public function publishAction()
    {
        $id = (int) $this->_arrParam['id'];
        $status = (int) $this->_arrParam['status'];
        $status = ($status == 1) ? 2 : 1;
        $data = array(
            'status'=>$status,
        );
        $this->_model->updateNews($data, $id);
        $this->_redirect($_SERVER['HTTP_REFERER']);
    }

    public function searchAction()
    {
        $strFlex = new Zendvn_Filter_RemoveCircumflex();
        $title = strtolower(trim(strip_tags($this->_arrParam['title'])));
        $status = (int) $this->_arrParam['status'];
        $this->view->keyword = array(
            'title'=>$title,
            'status'=>$status,
        );
        $data = array(
            'title'=>(string) '%'.str_replace(' ','%',$strFlex->filter($title)).'%',
            'status'=>$status,
        );
        $adapter = new Zend_Paginator_Adapter_DbSelect($this->_model->searchNews($data, $this->_locale));
        $paginator = new Zend_Paginator($adapter);
        $paginator->setItemCountPerPage(40);
        $paginator->setPageRange(5);
        $currentPage = $this->_request->getParam('page', 1);
        $paginator->setCurrentPageNumber($currentPage);
        $this->view->data = $paginator;
        $this->view->total = $paginator->getTotalItemCount();
    }
}
